using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

using Alone.GameObjects;

namespace Alone.Handlers
{
	/// <summary>
	/// This is a game component that implements IUpdateable.
	/// </summary>
	public class NetworkHandler : Microsoft.Xna.Framework.GameComponent
	{
		private const int updateEveryFrame = 4;

		private NetworkSession networkSession;
		private IPlayerHandler playerHandler;
		
		private PacketWriter packetWriter;
		private PacketReader packetReader;
		
		private float frameUpdateThreshold;
		private int counter = 0;

		public NetworkHandler(Game game)
			: base(game)
		{
			// TODO: Construct any child components here
		}

		/// <summary>
		/// Allows the game component to perform any initialization it needs to before starting
		/// to run.  This is where it can query for any required services and load content.
		/// </summary>
		public override void Initialize()
		{
			networkSession = (NetworkSession)Game.Services.GetService(typeof(NetworkSession));
			playerHandler = (IPlayerHandler)Game.Services.GetService(typeof(IPlayerHandler));
			
			packetWriter = new PacketWriter();
			packetReader = new PacketReader();

			frameUpdateThreshold = (1000 / Game.GraphicsDevice.DisplayMode.RefreshRate) * updateEveryFrame;
						
			base.Initialize();
		}

		/// <summary>
		/// Allows the game component to update itself.
		/// </summary>
		/// <param name="gameTime">Provides a snapshot of timing values.</param>
		public override void Update(GameTime gameTime)
		{
			counter += gameTime.ElapsedGameTime.Milliseconds;

			if (counter > frameUpdateThreshold)
			{
				//LocalNetworkGamer gamer = networkSession.LocalGamers[0];
				//LocalPlayer player = playerHandler.

				//packetWriter.Write(player.Hp);
				//packetWriter.Write(player.Position);
				//packetWriter.Write(player.Rotation);
				//packetWriter.Write(player.State);

				counter = 0;
			}

			base.Update(gameTime);
		}
	}
}